<template>
  <m-switch :value="lock" active-text="解锁" inactive-text="锁定" @change="handleClick" v-if="getWharfId" />
</template>

<script>
import { wharfList, updateWharf } from '@/api/modules/inventory'
export default {
  props: {
    wharfId: {
      type: [Number, String],
      default: null,
    },
    validate: {
      type: Function,
      default: null,
    },
    value: {
      type: Boolean,
      default: false,
    },
    wharfCode: {
      type: String,
      default: null,
    },
  },
  computed: {
    getWharfId() {
      return this.wharfId || this.info.wharfId
    },
  },
  data() {
    return {
      lock: this.value,
      info: {},
    }
  },
  async mounted() {
    const { rows } = await wharfList({
      workStatus: 1,
      remark: this.$store.state.login.userInfo.userName,
    })
    if (rows.length) {
      this.info = rows[0]
      this.$emit('initWharfId', {
        id: this.info.wharfId,
        code: this.info.wharfCode,
      })
    }
    this.lock = rows.length !== 0
    this.$emit('input', this.lock)
  },
  methods: {
    async handleClick() {
      if (this.validate && !(await this.validate())) {
        return
      }

      const wharfId = this.getWharfId

      if (!wharfId) {
        uni.showToast({
          title: '请选择码头',
          icon: 'none',
        })
        return
      }
      await updateWharf({
        workStatus: this.lock ? 0 : 1,
        remark: this.lock ? '' : this.$store.state.login.userInfo.userName,
        wharfId,
        wharfCode: this.wharfCode || this.info.wharfCode,
      })

      uni.showToast({
        title: this.lock ? '解锁成功' : '锁定成功',
        icon: 'success',
      })

      this.lock = !this.lock
      this.$emit('input', this.lock)
    },
  },
}
</script>

<style lang="scss" scoped>
.switch {
  margin-right: 20rpx;
}
</style>
